package com.cell.common.exceptions;

import com.cell.common.Result;
import com.cell.common.States;
import com.cell.common.exceptions.exceptions.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * @author cloudJiang
 * @date 2022/6/24 9:14
 */
@ControllerAdvice
public class CommonExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result unknownException(Exception e) {
        return new Result(null, States.ERR_UNKNOWN.getStates(), States.ERR_UNKNOWN.getDescription());
    }

    /**
     * 处理实体字段校验不通过异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Result validationError(MethodArgumentNotValidException ex) {
        return new Result(null, States.ERR_BAD_REQUEST.getStates(), ex.getMessage());
    }

    /**
     * 处理普通异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler({PointAccountException.class, LoginAccountException.class, OrderException.class, UserException.class})
    @ResponseBody
    public Result commonError(ServiceException ex) {
        return new Result(null, ex.getStates(), ex.getMessage());
    }

    /**
     * 处理数据库异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({SQLException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Result sqlError(SQLException e) {
        return new Result(null, States.ERR_SQL.getStates(), States.ERR_SQL.getDescription());
    }
}
